package com.zzyl.nursing.util;

import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

public class IdCardUtils {
    private static final DateTimeFormatter BIRTHDAY_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter PARSE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");
    private static final int GENDER_INDEX = 16;
    private static final int BIRTHDAY_START_INDEX = 6;
    private static final int BIRTHDAY_END_INDEX = 14;

    public static int calculateAge(String idCard) {
        validateIdCard(idCard);
        LocalDate birthDate = parseBirthDate(idCard);
        return Period.between(birthDate, LocalDate.now()).getYears();
    }

    public static LocalDate getBirthday(String idCard) {
        validateIdCard(idCard);
        return parseBirthDate(idCard);
    }

    public static String getFormattedBirthday(String idCard) {
        return getBirthday(idCard).format(BIRTHDAY_FORMATTER);
    }

    public static int getGender(String idCard) {
        validateIdCard(idCard);
        char genderChar = idCard.charAt(GENDER_INDEX);
        return (genderChar - '0') % 2 == 1 ? 1 : 0;
    }

    private static LocalDate parseBirthDate(String idCard) {
        String birthDateStr = idCard.substring(BIRTHDAY_START_INDEX, BIRTHDAY_END_INDEX);
        return LocalDate.parse(birthDateStr, PARSE_FORMATTER);
    }

    private static void validateIdCard(String idCard) {
        if (Objects.isNull(idCard) || idCard.length() != 18) {
            throw new IllegalArgumentException("身份证号必须为18位");
        }
        try {
            Long.parseLong(idCard.substring(0, 17));
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("身份证号前17位必须为数字");
        }
    }
}
